package cn.shenshen.shop.service.impl;

import cn.shenshen.shop.domain.User;
import cn.shenshen.shop.mapper.UserMapper;
import cn.shenshen.shop.redis.MemberKeyPrefix;
import cn.shenshen.shop.redis.RedisService;
import cn.shenshen.shop.service.IUserService;
import cn.shenshen.shop.util.BusinessException;
import cn.shenshen.shop.util.DbUtil;
import cn.shenshen.shop.util.MemberCodeMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;//本来容器中没有,启动的时候会通过动态代理的方式帮我们去创建对应的bean

    @Autowired
    private RedisService redisService;

    public User selectById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    public String login(Long username, String password) {
        //根据用户名去查找用户信息
        User user = userMapper.selectByPrimaryKey(username);
        if (user==null){
            //抛出异常
            throw new BusinessException(MemberCodeMsg.USERNAME_PASSWORD_ERROR);
        }
        //密码校验
        String salt = user.getSalt();
        String dbPass = DbUtil.formPassToDbPass(password, salt);
        if ( ! dbPass.equals(user.getPassword())){
            //密码错误
            throw new BusinessException(MemberCodeMsg.USERNAME_PASSWORD_ERROR);
        }

        //登录操作成功
        String token = UUID.randomUUID().toString().replaceAll("-", "");//生成token
        redisService.set(MemberKeyPrefix.USER_TOKEN,token,user);//将信息保存到redis中去

        return token;

    }
}
